<template>
  <div class="hello">
    <div class="lailin">
      <el-input v-model="userInfo.userName" placeholder="请输入用户名"></el-input>
      <el-input v-model="userInfo.password" type="password" placeholder="请输入密码" style="margin-left: 20px"></el-input>
      <el-button type="primary" :loading="logining" style="margin-left: 20px" @click="login">{{logining?'登录中':'登录'}}
      </el-button>
    </div>
    <br/>
    <br/>
    <el-select v-model="project.ID" placeholder="请选择项目(可选)">
      <el-option
        v-for="item in projectList"
        :key="item.projectid"
        :label="item.projectname"
        :value="item.projectid">
      </el-option>
    </el-select>
    <span style="padding: 10px 20px">
      {{project.Name + '(' + project.ID + ')'}}
    </span>
    <el-input
      type="textarea"
      :rows="5"
      autosize
      placeholder="请输入日报内容,多条内容请以空格或回车分开,工时默认8h,项目默认第一条"
      v-model="workContent">
    </el-input>
    <br/><br/>


    <el-button-group style="margin-top: 30px">
      <el-button type="primary" icon="el-icon-edit" @click="thisDay">提交今日</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="thisWeek">提交本周</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="thisMonth">提交本月</el-button>
    </el-button-group>

  </div>
</template>

<script>
  import {Button, Input, Message, Loading,ButtonGroup,Select,Option} from 'element-ui';
  import localTools from 'src/utils/LocalStorageTools'

  export default {
    name: 'HelloWorld',
    data() {
      return {
        logining: false,
        userInfo: {
          userName: localTools.get('userInfo') ? localTools.get('userInfo').userName : '',
          password: localTools.get('userInfo') ? localTools.get('userInfo').password : ''
        },
        workContent: '',
        project: {
          ID: null,
          Name: null
        },
        projectList: []
      }
    },
    components: {
      [Button.name]: Button,
      [Input.name]: Input,
      [Message.name]: Message,
      [ButtonGroup.name]:ButtonGroup,
      [Loading.name]:Loading,
      [Select.name]:Select,
      [Option.name]:Option
    },
    watch: {
      'project.ID'(nv,ov) {
        if (nv && nv !== ov) {
          this.project.Name = this.projectList.filter(t=>t.projectid === nv)[0].projectname
        }
      }
    },
    methods: {
      login() {
        this.logining = true;
        this.api.login({
          username: this.userInfo.userName,
          password: this.userInfo.password,
          grant_type: "password",
          client_id: "A61AD336-3F5B-476C-A881-E1D3A9B4D513",
          lan: 'zh-CN'
        }).then(res => {
          Message.success('登录成功');
          this.logining = false;
          localTools.set('token', res);
          localTools.set('userInfo', this.userInfo);
        }).catch(t => {
          Message.error('登录失败,请检查用户名及密码是否正确');
          this.logining = false;
        })
      },
      thisWeek() {
        this.submit('1')
      },
      thisDay() {
        this.submit('0')
      },
      thisMonth() {
        this.submit('2')
      },

      //type : 区分
      // 当日日报(0)
      // 本周日报(1)
      // 本月日报(2)
      submit(type) {
        let temp = this.workContent.replace(/\s+/g, "");
        if (temp === '') {
          Message.error('请填写内容')
          return
        }
        if (this.project.ID === null || this.project.Name === null) {
          Message.error('请选择项目')
          return
        }
        if (localTools.get('token') === null || localTools.get('token') === undefined) {
          Message.error('请先登录')
          return
        }

        let listCount = 1;
        let dateList = [];
        if (type === '1') {
          let t = this.getDatesIn('week');
          dateList = this.getDates(this.reformate(t.start), this.reformate(this.end));
          listCount = dateList.length;
        }
        if (type === '2') {
          let t = this.getDatesIn('month');
          dateList = this.getDates(this.reformate(t.start), this.reformate(this.end));
          listCount = dateList.length;
        }
        let contents = this.workContent.split(/[\s\n]/);
        let submitParams = [];
        if (type !== '0') {
          if (contents.length >= dateList.length) {
            let j = '';
            for (let p = dateList.length - 1; p < contents.length; p++) {
              j += contents[p];
            }
            for (let i in dateList) {
              let t = {
                ProjectID: this.project.ID,
                ProjectName: this.project.Name,
                WorkingHours: 8,
                TodayContent: i === dateList.length - 1 ? j : contents[i],
                TomoContent: '',
                DailyHeaderID: ''
              }
              submitParams.push({
                DailyDate: dateList[i],
                detailarray: JSON.stringify(t)
              })
            }
          } else {
            for (let i in dateList) {
              let t = {
                ProjectID: this.project.ID,
                ProjectName: this.project.Name,
                WorkingHours: 8,
                TodayContent: i === contents.length - 1 ? contents[contents.length - 1] : contents[i],
                TomoContent: '',
                DailyHeaderID: ''
              }
              submitParams.push({
                DailyDate: dateList[i],
                detailarray: JSON.stringify(t)
              })
            }
          }
        } else {
          let t = {
            ProjectID: this.project.ID,
            ProjectName: this.project.Name,
            WorkingHours: 8,
            TodayContent: this.workContent,
            TomoContent: '',
            DailyHeaderID: ''
          }
          submitParams.push({
            DailyDate: this.formatDate(new Date()),
            detailarray: JSON.stringify(t)
          })
        }
        let ppt = [];
        for (let x in submitParams) {
          let tx = this.api.SaveDaily(submitParams[x]);
          ppt.push(tx)
        }
        let _this = this;
        let loadingInstance = Loading.service();
        Promise.all(ppt).then(res=>{
          console.log(res);
          _this.$nextTick(()=>{
            loadingInstance.close();
            Message.success('提交成功')
          })

        })
      },

      //type : 类型(month,week)
      //return 所选类型日期的开始和结束时间
      getDatesIn(type = 'month') {
        let curDate = new Date();
        let nowDayOfWeek = curDate.getDay() === 0 ? 7 : curDate.getDay();//今天本周的第几天
        let nowDay = curDate.getDate(); //当前日
        if (type === 'month') {
          let day = curDate.getDate() >= 10 ? curDate.getDate() : '0' + curDate.getDate()
          return {
            start: `${curDate.getFullYear()}-${curDate.getMonth() + 1}-01`,
            end: `${this.formatDate(curDate)}`
          }
        } else {
          let start = this.formatDate(new Date(curDate.getFullYear(), curDate.getMonth(), nowDay - nowDayOfWeek));
          let end = this.formatDate(curDate)
          return {
            start: start,
            end: end
          }
        }
      }
      ,
      //获取两个日期之间所有的工作日 除去周末和法定节假日(仅判断公历确定的)
      getDates(startDate, endDate) {
        let rej = []
        var festival = ["1-1", "5-1", "10-1", '10-2', '10-3'];//法定节假日
        for (
          let d = new Date(startDate.getTime());
          d.getTime() <= endDate.getTime();
          d.setDate(d.getDate() + 1)
        ) {
          if (d.getDay() != 0 && d.getDay() != 6 && festival.indexOf((d.getMonth() + 1) + "-" + d.getDate()) == -1)
            rej.push(this.formatDate(d))
        }
        return rej
      }
      ,
      formatDate(date) {
        let myyear = date.getFullYear();
        let mymonth = date.getMonth() + 1;
        let myweekday = date.getDate();

        if (mymonth < 10) {
          mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
          myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
      }
      ,
      reformate(dateString) {
        if (dateString) {
          dateString = dateString.replace(/-/g, '/')
          return new Date(dateString)
        }
        return new Date()
      }
    },
    created() {
      window._this = this;
      this.api.GetUserCommonProj().then(res => {
        if (res.code === '1000' && res.data && res.data.length > 0) {
          this.projectList = res.data || []
          if (res.data.some(item => item.selected === true)) {
            let t = res.data.filter(item => item.selected === true);
            this.project.ID = t[0].projectid;
            this.project.Name = t[0].projectname;
          } else {
            this.project.ID = res.data[0].projectid;
            this.project.Name = res.data[0].projectname;
          }
        }
      })
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .hello {
    display: flex;
    width: 100%;
    height: 100%;
    flex-direction: column;
    align-items: center;
  }

  .hello .lailin {
    display: flex;
    flex-direction: row;
    width: 100%;

  }
</style>
